package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstants;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型
     * @return
     */
    @Override
    public List<ShopType> queryTypeList() {
        log.info("展示店铺类型");
        log.info("查询缓存");
        String jsonList = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_TYPE_KEY);
        log.debug("jsonList:{}", jsonList);
        if(jsonList==null) {
            log.info("查询数据库");
            List<ShopType> shopTypeList = query().orderByAsc("sort").list();
            log.info("更新缓存");
            stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList));
            return shopTypeList;
        }
        if(jsonList.isBlank()) {
            return null;
        }
        log.info("查询缓存成功");
        List<ShopType> shopTypeList = JSONUtil.toList(jsonList, ShopType.class);
        return shopTypeList;
    }
}
